#!/usr/bin/env python

import datetime
import autorm.util
import autorm.model
import autorm.db.query

import resource as r

class Model(autorm.model.Model):
    '''Model class
    
    @author Julot <andy.julot@gmail.com>
    @since Wednesday, February 15, 2012. 01:47 PM'''
    
    class Attributes(object):
        '''Attributes class
        
        @author Julot <andy.julot@gmail.com>
        @since Saturday, February 25, 2012. 04:44 PM'''
    
        pass
    
    # This is using modified autorm with addition self.b_log_queries = False
    # to AutoConn
    db = autorm.util.AutoConn('%s.db' % r.string.app.name)
    
    @classmethod
    def get(cls, id):
        return cls.objects.get(id)
    
    def save(self):
        now = datetime.datetime.now()
        if self._new_record:
            self.insertTime = now
        self.updateTime = now
        return super(Model, self).save()
    
    @classmethod
    def createTable(cls):
        '''Create table'''
        
        cls.objects.create_table_if_needed()
    
    @classmethod
    def createIndex(cls):
        '''Create table index as determine in Meta'''
        
        if hasattr(cls.Meta, 'fields'):
            cmd = 'CREATE INDEX IF NOT EXISTS [index_%s_%s] ON [%s] ([%s] ASC);'
            for f in cls.Meta.fields:
                if f.index:
                    data = (cls.Meta.table, f.name, cls.Meta.table, f.name)
                    autorm.db.query.Query.raw_sql(cmd % data)
    
    @classmethod
    def dropIndex(cls):
        '''Drop index'''
        
        if hasattr(cls.Meta, 'fields'):
            cmd = 'DROP INDEX IF EXISTS [index_%s_%s];'
            for f in cls.Meta.fields:
                if f.index:
                    data = (cls.Meta.table, f.name)
                    autorm.db.query.Query.raw_sql(cmd % data)
    
    @classmethod
    def vacuum(cls):
        autorm.db.query.Query.raw_sql('VACUUM;')
    
    def getAttributes(self):
        attributes = self.Attributes()
        for field in self.Meta.fields:
            condition = hasattr(self, field.name)
            value = getattr(self, field.name) if condition else None
            setattr(attributes, field.name, value)
                
        return attributes
    
    def setAttributes(self, values):
        for field in self.Meta.fields:
            setattr(self, field.name, getattr(values, field.name))
        
    attributes = property(getAttributes, setAttributes)
    